﻿/*
* 公司：Leita Tech
* 版权信息：雷塔所有
* 任务：
* 描述：
* 作者：李大平
* 日期：2020/06/04
*
*/

#ifndef LTHttpRequester_H
#define LTHttpRequester_H

#include <QObject>

#include "model/LTModelDefines.h"

#ifndef LT_WASM
#include <QSslError>
#endif

class QNetworkReply;
class QNetworkRequest;
class QNetworkAccessManager;

//注意，不要手动调用QNetworkReply的read函数，因为LTHttpRequester已经读取过了，重复读取会导致读不到数据
class LTHttpRequester : public QObject
{
    Q_OBJECT
public:
    enum class Method
    {
        Get,
        Post,
        Put,
        Head,
    };

    explicit LTHttpRequester(QString url_string,
                           Method method = Method::Get,
                           QByteArray paras = QByteArray(),
                           QObject *parent = nullptr);
    ~LTHttpRequester();

    bool request(const QString& content_type = QString("json"));
    void setUrlString(QString url_string);
    QString getUrlString() const;
    void setUseProxy(bool val);
    bool getUseProxy() const;
#ifndef LT_WASM
    void setConfigureSsl(bool val);
    bool getConfigureSsl() const;
#endif
    void setMethod(Method val);
    Method getMethod() const;
    QByteArray getResponseData();
    void setParas(QByteArray val);
    QByteArray getParas() const;
    void setUseCache(bool val);
    bool getUseCache() const;
    void setTimeOut(int val);
    int getTimeOut() const;

    //QNetworkReply *getReply();
    void abort();
    QString errorString() const;
    QNetworkRequest *getRequest();
    QNetworkAccessManager *getNetworkAccessManager();
signals:
    void finished(QNetworkReply* rpy);
#ifndef LT_WASM
    void sslErrors(QNetworkReply *reply, const QList<QSslError> &errors);
#endif
    void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);

public slots:
#ifndef LT_WASM
    void onSslErrors(QNetworkReply *reply, const QList<QSslError> &errors);
#endif
private:
    QNetworkReply *reply_ = nullptr;
    QNetworkRequest *request_ = nullptr;
    QNetworkAccessManager *network_access_manager_ = nullptr;
    QString url_string_;
    bool use_proxy_ = false;
    bool configure_ssl_ = true;
    bool block_until_finished_ = true;
    Method method_ = Method::Get;
    QByteArray paras_;
    bool use_cache_ = true;
    int time_out_ = 3000;
};

#endif // LTHttpRequester_H
